package com.tencent.iov.cowin.befsale.clue.service.clue.impl;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.software.boot.common.model.dao.OrderField;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueIntentionAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueIntentionResponse;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueIntentionVehicleResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.ClueDictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.TenantClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.response.DictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueIntention;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueIntentionVehicle;
import com.tencent.iov.cowin.befsale.clue.domain.cus.vo.ClueDictionaryMapped;
import com.tencent.iov.cowin.befsale.clue.domain.cus.vo.ClueDictionaryMappedCollect;
import com.tencent.iov.cowin.befsale.clue.repository.clue.ClueIntentionManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueIntentionService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueIntentionVehicleService;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.boot.common.util.ValidateUtils;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Describe: 线索意向信息_Service实现层
 * @author: whp
 * @created: 2021-12-21 16:16:14
 * @version: 1.0
 */
@Service
public class ClueIntentionServiceImpl implements ClueIntentionService {

    @Autowired
    private ClueIntentionManager clueIntentionManager;
    @Autowired
    private TenantClient tenantClient;
    @Autowired
    private ClueDictionaryMappedCollect dictionaryMappedCollect;
    @Autowired
    private ClueIntentionVehicleService clueIntentionVehicleService;

    /**
     * 通过ID获取详细信息
     *
     * @param: request
     * @return: ClueIntention对象
     */
    @Override
    public ClueIntention getDetailById(Long id) {
        /** 1 验证请求参数 */
        ValidateUtils.checkLongGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueIntention clueIntention = clueIntentionManager.getDetailById(id);
        if (EmptyUtils.isNotEmpty(clueIntention)) {
            return BeanUtil.copy(clueIntention, ClueIntention.class);
        }
        /** 3 返回结果 */
        return null;
    }

    /**
     * 单条数据插入ClueIntention
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public int insert(ClueIntention request) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueIntentionManager.insert(request);
        /** 3 封装返回值 */
        return count;
    }

    /**
     * 批量插入ClueIntention
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<ClueIntention> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = clueIntentionManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }


    @Override
    public int update(ClueIntention request) {
        //验证请求参数
        ValidateUtils.checkObjNull(request, "参数为null");
        ValidateUtils.checkLongGTZero(request.getId(), "主键ID不可以为null");

        //处理业务
        request = ClueIntentionAssembler.initUpdateClueIntentionRequest(request);
        //返回对象
        return clueIntentionManager.update(request);
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(ClueIntention request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkLongNotNullAndGTZero(id, "ID不能为空或小于0");
        /** 2 处理业务 */
        ClueIntention clueIntention = new ClueIntention();
        clueIntention.setId(id);
//		clueIntention.setDelete(DeleteEnum.DETELED.getCode());
        int count = clueIntentionManager.update(clueIntention);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<ClueIntention> getListByParam(ClueIntention request) {
        /** 1 验证请求参数 */
        //可以设置排序

        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        /** 2 处理业务 */
        List<ClueIntention> queryList = clueIntentionManager.getListByParam(request);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, ClueIntention.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<ClueIntention> getPageByParam(PageRequest<ClueIntention> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());

        ClueIntention query = request.getParamData();
        query.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        query.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        query.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        Page<ClueIntention> queryPageList = clueIntentionManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<ClueIntention> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), ClueIntention.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    @Override
    public ClueIntentionResponse getOneByParam(ClueIntention request) {
        ValidateUtils.checkObjNull(request, "查询参数为null");

        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        ClueIntention clueIntention = clueIntentionManager.getOneByParam(request);
        if (EmptyUtils.isEmpty(clueIntention)) {
            return null;
        }
        ClueIntentionResponse clueIntentionResponse = ClueIntentionAssembler.transformPOToResponseVo(clueIntention, ClueIntentionResponse.class);
        clueIntentionResponse.setIntentionStr(this.getClueIntentionStr(clueIntention));
        //意向车系车型信息
        ClueIntentionVehicle queryVehicle = new ClueIntentionVehicle();
        queryVehicle.setClueId(clueIntention.getClueId());
        queryVehicle.setDeleted(DeleteEnum.INIT.getFlag());
        List<ClueIntentionVehicle> vehicles = clueIntentionVehicleService.getListByParam(queryVehicle);
        if (EmptyUtils.isNotEmpty(vehicles)) {
            clueIntentionResponse.setClueIntentionVehicles(BeanUtil.copyByList(vehicles, ClueIntentionVehicleResponse.class));
        }
        return clueIntentionResponse;
    }

    @Override
    public List<ClueDictionariesResponse> getClueIntentionDictionaries() {
        if (EmptyUtils.isEmpty(dictionaryMappedCollect.getIntentionTypes())) {
            throw new BusinessException(NEError.INVALID_PARAMETER, "意向字典信息不存在");
        }
        List<String> types = dictionaryMappedCollect.getIntentionTypes().stream().map(ClueDictionaryMapped::getType).collect(Collectors.toList());

        //查询获取字典信息
        QueryDictionariesRequest request = new QueryDictionariesRequest();
        request.setTypes(types);

        List<OrderField> list = new ArrayList<>();
        OrderField orderField = new OrderField("updated_time","asc");
        list.add(orderField);
        request.setOrderFields(list);

        Response<List<DictionariesResponse>> response = tenantClient.getDictionariesListByParam(request);
        if (!Response.CODE_SUCCESS.equals(response.getCode()) || EmptyUtils.isEmpty(response.getData())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "未查询到字典信息");
        }
        List<DictionariesResponse> dictionariesResponses = response.getData();
        //整理数据
        Map<String, List<DictionariesResponse>> dictionaryMap = dictionariesResponses.stream().collect(Collectors.groupingBy(DictionariesResponse::getType));
        if (EmptyUtils.isEmpty(dictionaryMap)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "处理字典信息失败");
        }
        List<ClueDictionariesResponse> clueDictionariesResponses = Lists.newArrayList();
        dictionaryMappedCollect.getIntentionTypes().forEach(clueDictionaryMapped -> {
            if (!dictionaryMap.containsKey(clueDictionaryMapped.getType()) || EmptyUtils.isEmpty(dictionaryMap.get(clueDictionaryMapped.getType()))) {
                return;
            }
            ClueDictionariesResponse clueDictionariesResponse = BeanUtil.copy(clueDictionaryMapped, ClueDictionariesResponse.class);
            clueDictionariesResponse.setDictionaries(dictionaryMap.get(clueDictionaryMapped.getType()));
            clueDictionariesResponses.add(clueDictionariesResponse);
        });
        return clueDictionariesResponses;
    }


    @Override
    public String getClueIntentionStr(ClueIntention clueIntention) {
        ValidateUtils.checkObjNull(clueIntention, "参数为null");
        List<ClueDictionaryMapped> intentionTypes = dictionaryMappedCollect.getIntentionTypes();
        if (EmptyUtils.isEmpty(intentionTypes)) {
            return "";
        }
        List<String> types = intentionTypes.stream().map(ClueDictionaryMapped::getType).collect(Collectors.toList());

        //查询获取字典信息
        QueryDictionariesRequest request = new QueryDictionariesRequest();
        request.setTypes(types);
        Response<List<DictionariesResponse>> response = tenantClient.getDictionariesListByParam(request);
        if (!Response.CODE_SUCCESS.equals(response.getCode()) || EmptyUtils.isEmpty(response.getData())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "未查询到字典信息");
        }
        return ClueIntentionAssembler.getIntentionTags(response.getData(), clueIntention);
    }
}
